package com.ronghui.cash.util.limu.demo;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ronghui.cash.util.limu.common.HttpClient;
import com.ronghui.cash.util.limu.common.MDUtil;
import com.ronghui.cash.util.limu.common.StringUtils;
import org.apache.http.message.BasicNameValuePair;

import java.util.*;
import java.util.Map.Entry;

/**
 * @Description:公积金
 * @author kx
 * @version v1.0
 */
public class HouseFundDemo {
	
	public static HttpClient httpClient = new HttpClient();
	
	public static final String apiUrl = "https://t.limuzhengxin.cn/api/gateway";
	public static final String apiKey = "1234255010601944";
	public static final String apiSecret = "gKJHomMTQs3456Zg77OPAfytBFmKTVJg";
	
	public static String token = null;
	public static final String version = "1.0.0";
	public static final long timeInterval = 5000;
	public static final String bizType = "housefund";
	public static final String method = "api.housefund.get";
	public static final String username = "admin";
	public static final String password = "admin123";
	public static final String area = "3100";
	
/*	public static void main(String[] args) throws Exception {
        System.out.println("开始获取公积金信息");
        //提交受理请求对象
        List<BasicNameValuePair> reqParam = new ArrayList<BasicNameValuePair>();
        reqParam.add(new BasicNameValuePair("method", method));//接口名称	是	api.mobile.sendSms
     
        reqParam.add(new BasicNameValuePair("apiKey", apiKey));//API授权
        
        reqParam.add(new BasicNameValuePair("callBackUrl", ""));//callBackUrl
        reqParam.add(new BasicNameValuePair("version", version));//调用的接口版本，可选值：1.0.0
        
       

        reqParam.add(new BasicNameValuePair("username", username));//账号
        reqParam.add(new BasicNameValuePair("password",  new String(Base64.encodeBase64(password.getBytes("UTF-8")))));//密码
        reqParam.add(new BasicNameValuePair("area", area));//地区
        reqParam.add(new BasicNameValuePair("realName", ""));//真实姓名
        reqParam.add(new BasicNameValuePair("sign", signConvert(strSplitJoint(reqParam), apiSecret)));//请求参数签名
        
        //提交受理请求
        String json = httpClient.doPost(apiUrl, reqParam);
        System.out.println("json=" + json);
        if(StringUtils.isBlank(json)) {
        	System.out.println("查询失败");
        } else {
	        ObjectMapper objectMapper = new ObjectMapper();
			JsonNode rootNode = objectMapper.readValue(json, JsonNode.class);
			String code = rootNode.get("code").textValue();
			
			
			if("0010".equals(code)) {//受理成功
				
				token = rootNode.get("token").textValue();
				timer();//每5秒查询一次数据请求
			} else {
				System.out.println("查询失败");
			}
        }
	}*/
	
	
	/**
	 * @Description:定时器
	 * @param @return 
	 * @throws
	 */
	public static void timer() {
		System.out.println("轮循 start");
		 final Timer timer = new Timer();
	        timer.schedule(new TimerTask() {  
	        	
	            public void run() {  
	            	   
						try {
							//循环取的状态，查询结果
							//停止循环(发送短信失败或信息查询成功)
							if(roundRobin()) {
								
								System.out.println("轮循 end");
								System.out.println("获取公积金信息结束");
								timer.cancel();// 停止定时器
								
							}
						} catch (Exception e) {
							e.printStackTrace();
							//异常
						}
						
	            }  
	        },0, timeInterval);
	       
	}
	/**
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws Exception 
	 * @Description:状态查询
	 * @param @param token
	 * @param @return 
	 * @throws
	 */
	public static String getSelectCode(String json) throws Exception {
        
		if(StringUtils.isBlank(json)) {
			return "";
		}
		
        ObjectMapper objectMapper = new ObjectMapper();
		JsonNode rootNode = objectMapper.readValue(json, JsonNode.class);
		String code = rootNode.get("code").textValue();
		return code;
	}
	
	
	/**
	 * @throws Exception 
	 * true 停止循环(发送短信失败或信息查询成功)，false:未取到结果集或成功取结果集
	 * @Description:循环取的状态，查询结果
	 * @param @param token
	 * @param @return 
	 * @throws
	 */
	public static boolean roundRobin() throws Exception {

		//状态查询
		String json = httpClient.doPost(apiUrl, getReqParam());
		String code = getSelectCode(json);
		System.out.println("循环取的状态:" + code);
		System.out.println("循环取的信息:" + json);
		
		if(StringUtils.isBlank(code)) {
			//未取到结果集
			return false;
		}
		
		if("0000".startsWith(code)) {//0000成功  0开头短信验证码
			  System.out.println("对象结果查询 >>>>>");
			  //发送对象结果查询
			  getData();
			  return true;
		} 
		
		if(code.startsWith("1")) {
			//公共错误码
			return true;
		}
		
		if(code.startsWith("30") || code.startsWith("31")) {
			//业务错误码
			return true;
		}
		
		
		//其他异常停止循环
		return true;
		
	
	}
	
	/**
	 * @Description:查询公积金的结果集(结果查询)
	 * @param  
	 * @throws
	 */
	public static void getData() {
		List<BasicNameValuePair> reqParam = new ArrayList<BasicNameValuePair>();
	    reqParam.add(new BasicNameValuePair("method", "api.common.getResult"));//接口名称	是	api.common.getResult
	    reqParam.add(new BasicNameValuePair("apiKey",apiKey));//API授权
	    reqParam.add(new BasicNameValuePair("version", version));//调用的接口版本，可选值：1.0.0
	    
	    
	    reqParam.add(new BasicNameValuePair("token", token));//请求标识
	    reqParam.add(new BasicNameValuePair("bizType", bizType));//手机短信验证码
	    
	    reqParam.add(new BasicNameValuePair("sign", signConvert(strSplitJoint(reqParam), apiSecret)));//请求参数签名
	    String json = httpClient.doPost(apiUrl, reqParam);
	    System.out.println("公积金的结果集:" + json);
	}
	
	/**
	 * @Description:获取状态
	 * @param @return 
	 * @throws
	 */
	public static List<BasicNameValuePair> getReqParam() {
		List<BasicNameValuePair> reqParam = new ArrayList<BasicNameValuePair>();
	    reqParam.add(new BasicNameValuePair("method", "api.common.getStatus"));//接口名称	是	api.mobile.sendSms
	    reqParam.add(new BasicNameValuePair("apiKey", apiKey));//API授权
	    reqParam.add(new BasicNameValuePair("version", version));//调用的接口版本，可选值：1.0.0
	    reqParam.add(new BasicNameValuePair("token", token));
	    reqParam.add(new BasicNameValuePair("sign", signConvert(strSplitJoint(reqParam), apiSecret)));//请求参数签名
	    return reqParam;
	}
    
    
	public static String signConvert(String sign,String key){
		
		
		Map<String, String> paramMap = new HashMap<String,String>();
		String ret = "";
		if(!StringUtils.isEmpty(sign)) {
			String[] arr = sign.split("&");
			for(int i = 0 ; i < arr.length;i++ ) {
				String tmp = arr[i];
				if(-1 != tmp.indexOf("=")) {
					paramMap.put(tmp.substring(0, tmp.indexOf("=")), tmp.substring(tmp.indexOf("=")+1,tmp.length()));
				}
				
			}
		}
		List<Entry<String,String>> list = new ArrayList<Entry<String,String>>(paramMap.entrySet());
		Collections.sort(list, new Comparator<Entry<String,String>>() {
			public int compare(Entry<String, String> o1, Entry<String, String> o2) {
				int ret = 0;
				ret = o1.getKey().compareTo(o2.getKey());
				if(ret > 0 ) {
					ret = 1;
				}else {
					ret = -1;
				}
				return ret;
			}
		});

		StringBuilder sb = new StringBuilder();
		for(Entry<String,String> mapping:list){
			if(!"sign".equals(mapping.getKey())) {
				sb.append(mapping.getKey()).append("=").append(mapping.getValue()).append("&");
			}
        } 
		sb.setLength(sb.lastIndexOf("&"));
		sb.append(key);
		ret = MDUtil.SHA1(sb.toString());
		
		//System.out.println(sb.toString());
		return ret;
	}
	
	public static String strSplitJoint(List<BasicNameValuePair> reqParam) {
		StringBuffer sb = new StringBuffer();
	       int index = 1;
	        for (BasicNameValuePair nameValuePair : reqParam) {
	        	sb.append(nameValuePair.getName() + "=" + nameValuePair.getValue());
	        	if(reqParam.size() != index) {
	        		sb.append("&");
	        	}
	        	index ++;
			}
	   return sb.toString();
	}
}
